import java.util.LinkedList;
import java.util.Queue;

/**
 * 695. 岛屿的最大面积
 * https://leetcode.cn/problems/max-area-of-island/description/
 */
class Solution {
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    boolean[][] vist;
    int m, n;
    public int maxAreaOfIsland(int[][] grid) {
        int ret = 0;
        m = grid.length;//行
        n = grid[0].length;//列
        vist = new boolean[m][n];

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1 && !vist[i][j]) {
                    ret = Math.max(ret, bfs(grid, i, j));
                }
            }
        }

        return ret;
    }

    public int bfs(int[][] grid, int i, int j) {
        int count = 0;
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{i, j});
        count++;
        vist[i][j] = true;
        while(!q.isEmpty()) {
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && grid[x][y] == 1) {
                    q.offer(new int[]{x, y});
                    count++;
                    vist[x][y] = true;
                }
            }
        }
        return count;
    }
}